package com.vanke.vms.management.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.vanke.vms.common.action.BaseAction;
import com.vanke.vms.common.domain.ForXls;
import com.vanke.vms.common.domain.Info;
import com.vanke.vms.common.domain.User;
import com.vanke.vms.management.service.XlsOpService;

public class XlsOpAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1986713158767567132L;

	private int returnMessage;

	private XlsOpService xlsOpService;

	private File xlsxFile;

	private List<String> headinfo;

	private List<List<String>> contentinfo;
	
	private List<ForXls> infoList;
	
	private List<ForXls> addInfoList;
	
	private String errMessage;

	private int role;


	public String jump(){
		User curUser = (User)session.get("user");
		if(curUser == null)
			return LOGIN;
		if(curUser.getGrade() == 2)
			role = 2;
		else if(curUser.getGrade() == 1)
			role = 1;
		else if(curUser.getGrade() == 0)
			role = 0;
		
		return SUCCESS;
	}
	
	private Map<String,String> initialMap(){
		 Map<String,String> map = new HashMap<String,String>();
		 map.put("楼盘名称","houseSet");
		 map.put("楼栋","houseBuild");
		 map.put("房号","houseNumber");
		 map.put("业主姓名","holderName");
		 map.put("联系电话1","holderPhone1");
		 map.put("联系电话2","holderPhone2");
		 map.put("电子邮件","holderEmail");
		 map.put("收件人姓名","receiverName");
		 map.put("联系地址","receiverAddress");
		 map.put("证件号码","holderIdno");
		 map.put("年","year");
		 map.put("月","month");
		 map.put("日","day");
		 map.put("农历(月)","monthyin");
		 map.put("农历(日)","dayyin");
		 map.put("建筑面积(平米)","houseArea");
		 map.put("装修类型(毛坯/装修)","houseDecType");
		 map.put("是否万科员工(是/否)","isVanker");
		 map.put("是否空置(是/否)","houseFreed");
		 map.put("是否为出租房(是/否)","houseLeted");
		 map.put("是否为二手房(是/否)","houseUsed");
		 map.put("是否为投资客(是/否)","isInvestor");
		 map.put("房修重点业主","FXfocus");
		 map.put("重点投诉业主","KFfocus");
		 map.put("物业重点业主","WYfocus");
		 map.put("是否发生过法律纠纷","lawIssue");
		 map.put("优乐卡号","youleCardNo");
		 map.put("优乐卡积分","youleCardScore");
		 map.put("优乐社区用户","youleCOmmunity");
		 map.put("社团成员","collegeMember");
		 map.put("楼盘属性","houseSetPro");
		 map.put("签约时间","contractedTime");
		return map;
	}
	
	public String importXls() throws IOException {
		returnMessage = 0;
		errMessage = "";
		FileInputStream ins = new FileInputStream(xlsxFile);
		XSSFWorkbook xwb = new XSSFWorkbook(ins);
		XSSFSheet sheet = xwb.getSheetAt(0);
		
		/*XSSFRow test = sheet.getRow(0);
		int testint =  test.getPhysicalNumberOfCells();
		if(test == null){
			System.out.println("null");
		}
		else if(test.getCell(1) == null){
			System.out.println("cell null");
		}
		else if(test.getCell(1).equals("")){
			System.out.println("cell empty");
		}*/
		// 定义 row、cell   
		XSSFRow row;   
		String cell;   
		List<String> pnameList = new ArrayList<String>();
		List<String> cnameList = new ArrayList<String>();
		
		addInfoList = new ArrayList<ForXls>();
		infoList = new ArrayList<ForXls>();
		
		Map<String,String> map = initialMap();
		
		int pnameRow = sheet.getFirstRowNum()+3;
		XSSFRow row1 = sheet.getRow(pnameRow);
		XSSFRow row2 = sheet.getRow(pnameRow+1);
		for(int i = 0; i < row1.getPhysicalNumberOfCells() && row1.getCell(i)!= null ; i++){//get Pname(大类的名字/只有一类的名字)
			cell = row1.getCell(i).toString();
			if((cell.equals("") || cell == null) && i>0){//如果pname的cell为空，那么说明可能是2层的。
				if(row2.getCell(i) == null)
					break;
				else if(row2.getCell(i).toString().equals(""))//如果上下两层都是空，那么就是到头了
					break;
				String thisCell = pnameList.get(i-1);
				pnameList.add(thisCell);
			}
			else{
				pnameList.add(cell);
			}
		}
		for(int i = 0; i < row2.getPhysicalNumberOfCells() && row2.getCell(i)!= null ; i++){//get Cname(小类的名字/只有一类的话就是空字符)
			cell = row2.getCell(i).toString();
			if(cell.equals("") || cell == null){
				cnameList.add("");
				continue;
			}else{
				cnameList.add(cell);
			}
		}
		
		int totalNumberOfCells = pnameList.size()>cnameList.size()?cnameList.size():pnameList.size();
			//row1.getPhysicalNumberOfCells();//这个变量是为了避免 excel后边的空的列也可能被认为是有数据的
		//这个循环是把excel列名对应的info的英文名或者addinfo的pname cname放入对应的list
		for(int i=0;i<totalNumberOfCells;i++){
			String curName = pnameList.get(i);
			if(curName.equals("交付阶段")||curName.equals("入住阶段")||curName.equals("房屋报修")||curName.equals("投诉")||curName.equals("咨询")||curName.equals("满意度回访")){
				//addInfo的列，设置no,pname, cname
				ForXls tmpNode = new ForXls();
				tmpNode.setNo(i);
				tmpNode.setPname(curName);
				tmpNode.setCname(cnameList.get(i));
				addInfoList.add(tmpNode);
			}
			else if(curName.equals("投诉情况")||curName.equals("社区属性")||curName.equals("销售阶段")){
				ForXls tmpNode = new ForXls();
				tmpNode.setNo(i);
				tmpNode.setPname(map.get(cnameList.get(i)));//这3个当做普通info处理，把第二行的名字放入pname，第一行不管它
				infoList.add(tmpNode);
			}
			else{
				//普通的Info的列，只设置no和英文列名
				//String curKey = map.get(cnameList.get(i));
				String curKey = map.get(curName);
				if(curKey == null){
					returnMessage = 1;
					errMessage = "您上传的excel列名有问题,请修改>>"+ curName +"<<的列名并重新上传";
					if(ins != null ) ins.close();
					return "error";
				}
				ForXls tmpNode = new ForXls();
				tmpNode.setNo(i);
				tmpNode.setPname(curKey);
				infoList.add(tmpNode);
			}
		}
		//这个循环是为了确认那3个决定infoid的key是否都有，如果没有的话，就返回错误的提示，说此excel不能导入
		int noerror = 3;
		for(int i = 0;i<infoList.size();i++){
			if(infoList.get(i).getPname().equals("houseSet") ||infoList.get(i).getPname().equals("houseBuild") ||infoList.get(i).getPname().equals("houseNumber"))
				noerror--;
		}
		if(noerror>0){
			returnMessage = 2;
			if(ins != null ) ins.close();
			return "error";
		}
		
		/////////////////要按照GF的那个excel的结构和名称来
		//获取其他数据
		List<List<String>> infoValueList = new ArrayList<List<String>>();
		List<List<String>> addInfoValueList = new ArrayList<List<String>>();
		for(int i=5;i < sheet.getPhysicalNumberOfRows(); i++) {
			row = sheet.getRow(i);
			List<String> curInfoList = new ArrayList<String>(); 
			for(int j=0;j<infoList.size();j++){
				XSSFCell tmpXSSFCell = row.getCell(infoList.get(j).getNo());
				if(tmpXSSFCell == null)
					cell = "";
				else
					cell = tmpXSSFCell.toString();
				curInfoList.add(cell);
			}
			infoValueList.add(curInfoList);
			
			List<String> curAddInfoList = new ArrayList<String>();
			for(int j=0;j<addInfoList.size();j++){
				XSSFCell tmpXSSFCell = row.getCell(addInfoList.get(j).getNo());
				if(tmpXSSFCell == null)//存在空数据
					cell = "";
				else
					cell = tmpXSSFCell.toString();
				curAddInfoList.add(cell);
			}
			addInfoValueList.add(curAddInfoList);
		}
		//删除临时文件
		if(ins != null ) ins.close();
		
		xlsOpService.importInfo(infoList, infoValueList, addInfoList, addInfoValueList);
		returnMessage = 4;
		return SUCCESS;
	}

	// //////////////////////////////////////////////////////////
	
	public int getRole() {
		return role;
	}

	public void setRole(int role) {
		this.role = role;
	}
	
	public String getErrMessage() {
		return errMessage;
	}

	public void setErrMessage(String errMessage) {
		this.errMessage = errMessage;
	}
	
	public int getReturnMessage() {
		return returnMessage;
	}

	public void setReturnMessage(int returnMessage) {
		this.returnMessage = returnMessage;
	}
	
	public File getXlsxFile() {
		return xlsxFile;
	}

	public void setXlsxFile(File xlsxFile) {
		this.xlsxFile = xlsxFile;
	}

	public List<String> getHeadinfo() {
		return headinfo;
	}

	public void setHeadinfo(List<String> headinfo) {
		this.headinfo = headinfo;
	}

	public List<List<String>> getContentinfo() {
		return contentinfo;
	}

	public void setContentinfo(List<List<String>> contentinfo) {
		this.contentinfo = contentinfo;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public XlsOpService getXlsOpService() {
		return xlsOpService;
	}

	public void setXlsOpService(XlsOpService xlsOpService) {
		this.xlsOpService = xlsOpService;
	}
}
